<?php

namespace backend\models;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use common\models\AdminLog;
use common\models\AR;

/**
 * Site controller
 */
class BackendController extends Controller {

    public $admin;

    public function init() {
        parent::init();
        $this->admin = Yii::$app->user->identity;
    }

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error', 'frame', 'page'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * 记录管理员操作日志
     * @param mixed $info 操作日志|数据模型类
     */
    public function adminLog($info) {
        if (!is_string($info)) {
            $log = '';
            if (isset($info->name)) {
                $actionMap = [
                    'create' => '新建',
                    'update' => '更新',
                    'delete' => '删除',
                ];

                $actionName = $this->action->id;
                array_key_exists($actionName, $actionMap) && $log = "{$actionMap[$actionName]}{$info->modelName}：{$info->name}";
            }
        } else {
            $log = $info;
        }

        $admin = new AdminLog(['info' => $log,'system_type'=>$this->admin->currentSystem,'supplier_id'=>$this->admin->supplier_id]);
        $admin->save();
    }

    /**
     * 输出JSON
     * @param mix $content 输出内容
     * @param boolean $result 执行结果 默认为 true
     */
    public function renderJSON($content,$result=true) {
        $this->json(['result' => $result, 'content' => $content]);
    }

    public function json($param){
        echo \yii\helpers\Json::encode($param);
        Yii::$app->end();
    }
    
    /**
     * 页面输出JS
     * @param string $js 
     */
    public function js($js){
        echo '<script>'.$js.'</script>';
        Yii::$app->end();
    }
}
